package cn.keduox.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import cn.keduox.entity.OrderExtm;
import cn.keduox.utils.JDBCUtils;
import cn.keduox.utils.Result;

/**
 * 订单持久层
 * 
 * @author 邓中亚
 *
 */
public class OrderDao {
	// 声明需要用到的对象

	ResultSet rs = null;
	PreparedStatement ps = null;
	Connection con = null;

	/**
	 * 添加订单的页面选择
	 * 
	 * @param userId
	 * @return
	 */

	public Result addOrderPage(String userId) {
		Result result = new Result();
		result.setState(true);
		try {
			// 1.加载驱动
			// 2.获取连接
			con = JDBCUtils.getConnection();
			// 根据登录id去数据库查找该用户是否是会员
			String sql = "SELECT * FROM `user` WHERE `id`=?";
			ps = con.prepareStatement(sql);
			JDBCUtils.setObject(ps, userId);
			rs = ps.executeQuery();
			// 不是会员返回result去登录页面
			if (!rs.next()) {
				result.setState(false);
				result.setMessage("goLogin");
				return result;
			}
			// 是会员则判断该用户是否有收货地址
			sql = "SELECT * FROM `order_extm` WHERE `user_id`=?";
			ps = con.prepareStatement(sql);
			JDBCUtils.setObject(ps, userId);
			rs = ps.executeQuery();
			// 没有收货地址则返回result去填写收货地址页面
			if (!rs.next()) {
				result.setState(false);
				result.setMessage("goExtm");
				return result;
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			JDBCUtils.close(con, ps, rs);
		}
		result.setMessage("goAddOrder");
		return result;
	}

	/**
	 * 查找该用户的收货地址
	 * 
	 * @param userId
	 * @return
	 */
	public OrderExtm findExtm(String userId) {
		OrderExtm orderExtm = new OrderExtm();

		try {
			// 1.加载驱动
			// 2.获取连接
			con = JDBCUtils.getConnection();
			// 根据登录id去数据库查找该用户的收货地址
			String sql = "SELECT * FROM `order_extm` WHERE `user_id`=?";
			ps = con.prepareStatement(sql);
			JDBCUtils.setObject(ps, userId);
			rs = ps.executeQuery();
			//接收收货地址
			while (rs.next()) {
				orderExtm.setExtmName(rs.getString("extm_name"));
				orderExtm.setExtmAddress(rs.getString("extm_address"));
				orderExtm.setExtmCode(rs.getString("extm_code"));
				orderExtm.setExtmTele(rs.getString("extm_tele"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		return orderExtm;
	}

}
